<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use _PHPStan_b8e553790\Nette\Neon\Exception;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 客户标签创建
 * @Controller
 */
class ClientLabelCreate extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/client/labelCreate", methods="POST")
     */
    public function handle()
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        if (!empty($data['tagName'])) {
            foreach ($data['tagName'] as $tag) {
                $t=Db::table('client_label')
                    ->where('client_label_group_id', $data['groupId'])
                    ->where('name', $tag)
                    ->first();
                if (!empty($t)) {
                    throw new CommonException(ErrorCode::SERVER_ERROR, '标签已存在');
                }
                Db::table('client_label')
                    ->insert([
                        'client_label_group_id' => $data['groupId'],
                        'name' => $tag,
                    ]);
            }
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    public function rules(): array
    {
        return [
            'groupName' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'groupName.required' => '分组名称必传',
        ];
    }
}
